<template>
  <el-container>
    <el-header><h1>在线转换excel</h1></el-header>
    <el-main>
      <el-upload
        class="upload-demo"
        action=""
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :before-upload="beforeUpload"
        multiple
        :limit="3"
        :on-exceed="handleExceed"
        :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xls</div>
      </el-upload>
      <el-button size="small" type="primary" id="export-table" @click="exportFunc">下载XLS</el-button>
    <div id="out-table" class="el-table el-table--fit el-table--enable-row-hover el-table--enable-row-transition">
      <table>
        <tr>
          <th width="180">教工号</th>
          <th width="100">姓名</th>
          <th width="100">部门</th>
          <th width="50">进校次数</th>
          <th width="400">进校时间</th>
          <th width="50">出校次数</th>
          <th width="400">出校时间</th>
        </tr>
        <template v-for="item in tableData">
          <template v-if="item.num >1">
          <tr>
            <td :rowspan="item.num">{{item['教工号']}}</td>
            <td :rowspan="item.num">{{item['姓名']}}</td>
            <td :rowspan="item.num">{{item['部门']}}</td>
            <td :rowspan="item.num">{{item['进校次数']}}</td>
            <td v-if="item['进校时间'].length>0">{{item['进校时间'][0]+'.'}}</td>
            <td v-else></td>
            <td :rowspan="item.num">{{item['出校次数']}}</td>
            <td v-if="item['出校时间'].length>0">{{item['出校时间'][0]+'.'}}</td>
            <td v-else></td>
          </tr>
          <template v-for="key in item.num">
            <tr v-if="key>0">
              <td v-if="item['进校时间'][key]">{{item['进校时间'][key]+'.'}}</td>
              <td v-else></td>
              <td v-if="item['出校时间'][key]">{{item['出校时间'][key]+'.'}}</td>
              <td v-else></td>
            </tr>
          </template>
          </template>
          <template v-else>
          <tr>
            <td >{{item['教工号']}}</td>
            <td>{{item['姓名']}}</td>
            <td>{{item['部门']}}</td>
            <td>{{item['进校次数']}}</td>
            <td v-if="item['进校时间'].length>0">{{item['进校时间'][0]+'.'}}</td>
            <td v-else></td>
            <td >{{item['出校次数']}}</td>
            <td v-if="item['出校时间'].length>0">{{item['出校时间'][0]+'.'}}</td>
            <td v-else></td>
          </tr>
          </template>
        </template>
        
      </table>
      
  </div>

    </el-main>
  </el-container>
      
  
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver';


export default {
  name: 'Excel',
  components: {
  },
  data () {
    return {
      fileList: [],
      tableData: [],
      loading: true,
      Obj: {},
      date: ''
    }
  },
  methods: {
    handleRemove(file, fileList) {
        // console.log(file, fileList);
    },
    handlePreview(file) {
        // console.log(file);
    },
    handleExceed(files, fileList) {
      // console.log(files);
        // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeUpload(file){
      let loading = this.$loading({
          lock: true,
          text: 'Loading'
      });
      var fileReader = new FileReader();
      let that = this
      this.date = file.name.replace('人脸识别教师考勤记录导出_', '').replace('.xls', '').replace(/\s*/g,"")

      fileReader.onload = function(ev) {
        try {
            var data = ev.target.result,
                workbook = XLSX.read(data, {
                    type: 'binary'
                }), // 以二进制流方式读取得到整份excel表格对象
                persons = []; // 存储获取到的数据
        } catch (e) {
          loading.close()
          this.$message.warning(`文件类型不正确`);
          return;
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        var fromTo = '';
        // 遍历每张表读取
        for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
                fromTo = workbook.Sheets[sheet]['!ref'];
                
                persons =     persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                                // break; // 如果只取第一张表，就取消注释这行
            }
        }
        loading.close()
        that.dealData(persons);
      };
      fileReader.readAsBinaryString(file);

      return false
    },
    deleteHref(string){
      // console.log(string)
      if(string == '' || string == '-') {
        return ''
      }
      let arr = string.split(/[\r\n]/)
      let tm = [], tm1 = []
      let j = [], c = []
      let reg =/[\u4e00-\u9fa5]/g;

// console.log(arr)
      for(let i in arr) {
        if(arr[i] == ''|| arr[i] == '-')continue;
        tm = arr[i].split('http')
        if(tm.length >0) {
          tm1 = tm[0].split(/[\r\n]/)
          for (let ii in tm1) {
            var true_time = parseInt(tm1[ii].substr(10, 9).replace(':', '').replace(':', ''))
            // console.log(true_time)
            if(true_time < 80000 || (true_time > 113000 && true_time < 145000) || true_time > 172000)continue
            if(tm1[ii].indexOf('出') >=0) {
              c.push(tm1[ii].substr(0, 19) + ",")
            }else{
              j.push(tm1[ii].substr(0, 19) + ",")
            }
          }
          
        }

      }
      
      return {c, j}
    },
    dealData(list){
      console.log(list)
      this.tableData = []

// return;
      let Obj = {}, detail= {};
      let temp, tt, date;
      let jin_num = 0, chu_num = 0
      let jin = '', chu  = ''
      for(let i in list){
        jin_num = 0, chu_num = 0
        jin = '', chu  = '', detail = {}

        tt = list[i]
        if(!tt['详细记录'] || tt['详细记录'] == '-' || tt['详细记录'] =='')continue
        date = tt['详细记录'].split(' ')[0]
        detail = this.deleteHref(tt['详细记录'])
        
        // return
        chu_num = detail.c.length
        jin_num = detail.j.length
        chu = detail.c//.join('\r\n')
        jin = detail.j//.join('\r\n')
        
// console.log(jin)
        if(tt['学号/工号']) {
          temp = tt
          if(!Obj.hasOwnProperty(temp['学号/工号'])) {
            Obj[temp['学号/工号']] = {
              '教工号': temp['学号/工号'],
              '姓名': temp['姓名'],
              '部门': temp['班级/部门'],
              '进校次数': jin_num,
              '进校时间': jin,
              '出校次数': chu_num,
              '出校时间': chu
            }
          }else{
            Obj[temp['学号/工号']]['进校时间'] += jin
            Obj[temp['学号/工号']]['进校次数'] += jin_num
            Obj[temp['学号/工号']]['出校时间'] += chu
            Obj[temp['学号/工号']]['出校次数'] += chu_num
          }
        }else{
          Obj[temp['学号/工号']]['进校时间'] += jin
          Obj[temp['学号/工号']]['进校次数'] += jin_num
          Obj[temp['学号/工号']]['出校时间'] += chu
          Obj[temp['学号/工号']]['出校次数'] += chu_num
        }
        if(tt['学号/工号']== '15955180132' || (temp && temp.hasOwnProperty('学号/工号') && temp['学号/工号']== '15955180132')) {
          console.log(Obj[temp['学号/工号']])
          console.log(jin_num)
        }

        
        
      }
      console.log(Obj)

      let a = []
      // let qObj = this.Obj
      // for(let i in Obj){
      //   temp = Obj[i]
      //   if(qObj.hasOwnProperty(i)) {
      //     a = this.getFirstValue(temp['list'])
      //     qObj[i]['list'][a[0]] = a[1]
      //   }else{
      //     qObj[i] = temp
      //   }
      //   // a = 0
      //   // for (let ii in Obj[i]['list']) {
          
      //   //   temp['list1'][a] = (Obj[i]['list'][ii])
      //   //   a ++
      //   // }
        
      // }
      // this.Obj = qObj
      
      for(let i in Obj){
        temp = Obj[i]
        temp['进校时间'] = this.myTrim(temp['进校时间'])
        temp['出校时间'] = this.myTrim(temp['出校时间'])
        if(temp['进校时间'].indexOf(',')>=0) {
          temp['进校时间'] = (temp['进校时间']).split(',')
        }
        if(temp['出校时间'].indexOf(',')>=0) {
          temp['出校时间'] = (temp['出校时间']).split(',')
        }
        if(temp['进校次数']> temp['出校次数']) {
          temp['num'] = temp['进校次数']
        }else{
          temp['num'] = temp['出校次数']
        }
        if(typeof temp['进校时间'] == 'string') {
          temp['进校时间'] = [temp['进校时间']]
        }
        if(typeof temp['出校时间'] == 'string') {
          temp['出校时间'] = [temp['出校时间']]
        }
        if(temp['教工号'] == '15955180132')console.log(temp)
        this.tableData.push(temp)
      }
      
      // console.log(this.tableData)
    },
    getFirstValue(list){
      for(let i in list){
        return [i, list[i]]
      }
    },
    myTrim(str) {
      if(!str || str == '')return str;
      if(typeof str != 'string') {
        // console.log(this.myTrim(str[0]))
        return this.myTrim(str[0]);
      }
      return str.substr(0,str.length-1);
    },
    exportFunc: function(e) {
      // 从表生成工作簿对象
      var wb = XLSX.utils.table_to_book(document.getElementById('out-table'));
      wb['Sheets']['Sheet1']['!cols'] = [{wpx: 90},
    {wpx: 50},
    {wpx: 60},
    {wpx: 60},
    {wpx: 120},
    {wpx: 60},
    {wpx: 120}]
    let temp;
    for(let i in wb['Sheets']['Sheet1']){
      if(i.indexOf('E') <0 && i.indexOf('G')<0) continue;

      temp = wb['Sheets']['Sheet1'][i]

      // wb['Sheets']['Sheet1'][i]['h'] = "<br style='mso-data-placement:same-cell;'/>aaaaaa"
      // wb['Sheets']['Sheet1'][i]['r'] = "aasssddaaaa"

    }
      console.log(wb)
      // 得到二进制字符串作为输出
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'binary'
      });
      
      FileSaver.saveAs(new Blob([this.s2ab(wbout)], {
        type: 'application/octet-stream'
      }), this.getFileName() + '.xlsx');
    },
    s2ab: function(s) {
      var cuf;
      var i;
      if (typeof ArrayBuffer !== 'undefined') {
        cuf = new ArrayBuffer(s.length);
        var view = new Uint8Array(cuf);
        for (i = 0; i !== s.length; i++) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return cuf;
      } else {
        cuf = new Array(s.length);
        for (i = 0; i !== s.length; ++i) {
          cuf[i] = s.charCodeAt(i) & oxFF;
        }
        return cuf;
      }
    },
    getFileName(){
      var nowDate = new Date();

      var year = nowDate.getFullYear();
      var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
  : nowDate.getMonth() + 1;
      var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
  .getDate();
      return year + "-" + month + "-" + day;
    }
  }
};
</script>

<style lang="less">
#export-table{ float:right;}
.tableDateList-p{width:30%; float:left;}
</style>
